package www.dianbaozu.com.ui.server

import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
import android.os.Bundle
import android.os.Parcelable
import android.view.View
import androidx.fragment.app.viewModels
import androidx.lifecycle.lifecycleScope
import com.netease.nim.uikit.api.NIMHelper
import com.netease.nim.uikit.xpopup.CreateXPopupHelper
import com.netease.nim.uikit.xpopup.PopupViewEntity
import dagger.hilt.android.AndroidEntryPoint
import www.dianbaozu.com.R
import www.dianbaozu.com.databinding.FragmentServerSettingsBinding
import www.dianbaozu.com.extension.requestUniversally
import www.wen.com.common.lib.base.fragment.BaseLoadingFragment
import www.wen.com.common.lib.base.module.BaseApiViewModel
import www.wen.com.common.lib.base.module.BaseViewModel
import www.wen.com.common.lib.data.entities.ServerGroupIncludeEntity
import www.wen.com.common.lib.data.entities.ServerInfo
import www.wen.com.common.lib.data.entities.ServerUpdateInfoEntity
import www.wen.com.common.lib.data.entities.ViewPagePosition
import www.wen.com.common.lib.extension.*
import www.wen.com.common.lib.extension.glide.setImageUrl
import www.wen.com.common.lib.helper.loading.KeyHelper
import www.wen.com.common.lib.helper.loading.KeyHelper.BUNDLE_DATA
import www.wen.com.common.lib.helper.loading.KeyHelper.BUNDLE_SERVER_ID
import www.wen.com.common.lib.helper.loading.TitleBarUniversalAdapter


/**
 * @author WEN
 * @Description:创建频道
 * @date 2020//25 17:48
 */
@AndroidEntryPoint
class ServerSettingsFragment : BaseLoadingFragment<FragmentServerSettingsBinding>(),
        View.OnClickListener {

    private lateinit var mServerInfo: ServerInfo

    private val mBaseApiViewModel: BaseApiViewModel by viewModels()

    override val viewModel: BaseViewModel
        get() = mBaseApiViewModel

    override fun isEnableLoadingHelper() = true

    override fun getTitleBarUniversalAdapter(): TitleBarUniversalAdapter = TitleBarUniversalAdapter(
            requireActivity(),
            tilte = getString(R.string.server_setting),
            action = ::titleAction
    )

    override fun getLayoutId(): Int = R.layout.fragment_server_settings

    override fun lazyInitView() {
        mServerInfo = requireArguments().getParcelable(BUNDLE_DATA)!!
        dataBinding.run {
            setImageUrl(ivAvatar, mServerInfo.serverLogo.imgUrl())
            tvServerName.text = mServerInfo.serverName
            tvServerID.text = mServerInfo.serverId
            tvServerIntroduce.text = mServerInfo.serverIntro
        }
        observeListen()
    }

    private fun observeListen() {
        //更新头像、服务器名字
        observeObject(KeyHelper.UPDATE_SERVER_INFORMATION_KEY, this, ServerUpdateInfoEntity::class.java) {
            dataBinding.run {
                serverName?.also { tvServerName.text = it }
                serverLogo?.also { setImageUrl(ivAvatar, it.imgUrl()) }
                serverIntro?.also { tvServerIntroduce.text = it }
            }
        }
    }

    override fun onClick(v: View) {
        when (v.id) {
            R.id.slAvatar,
            R.id.clAvatar -> {
                nav(R.id.action_serverSettingsFragment_to_updateServerLogoFragment, Bundle().apply {
                    putParcelable(BUNDLE_DATA, mServerInfo)
                })
            }
            R.id.clServerName -> {
                nav(R.id.action_serverSettingsFragment_to_changeUseNameInServerFragment, Bundle().apply {
                    putParcelable(BUNDLE_DATA, mServerInfo)
                })
            }
            R.id.tvClickCopy -> {
                val clipboard = requireActivity().getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
                val clip = ClipData.newPlainText("simple_text", mServerInfo.serverId)
                clipboard.setPrimaryClip(clip)
                toast("复制成功")
            }
            R.id.clChannelManagement -> channelManagement()
            R.id.tvServerIntroduce -> {
                nav(R.id.action_serverSettingsFragment_to_changeServerIntroduceFragment, Bundle().apply {
                    putParcelable(BUNDLE_DATA, mServerInfo)
                })
            }

            R.id.tvDeleteServer -> {
                CreateXPopupHelper.createShowStandardAlertPopupView(PopupViewEntity().apply {
                    context = requireActivity()
                    standardAlertPopupViewTitle = getString(R.string.com_delete_server)
                    isShow = true
                    standardAlertPopupViewCancelContent = "取消"
                    standardAlertPopupViewConfirmContent = "删除"
                    standardAlertPopupViewContent = "你确定要删除【${mServerInfo.serverName}】吗？\n该操作无法撤销"
                    confirmFunction = {
                        mBaseApiViewModel.requestUniversally(
                                viewModelScope = lifecycleScope,
                                tipLoading = getString(R.string.com_deleting),
                                tipSuccess = getString(R.string.com_delete_succeeded),
                                isShowToastTip = false,
                                request = { appDataManage ->
                                    appDataManage.requestDeleteServer(mServerInfo.serverId)
                                }
                        ) { info ->
                            mServerInfo.teamIds?.forEach {
                                NIMHelper.updateTeamUnreadCount(it,0)
                            }
                            NIMHelper.updateAddFriendUnreadCount()
                            it.dismiss()
                            //刷新首页服务列表,避免点击到已经删除的服务器
                            postObject(KeyHelper.REFRESHING_SERVER_LIST, Object())
                            //回到首页-服务器
                            postObject(KeyHelper.MAIN_VIEWPAGER_POSITION_KEY, ViewPagePosition(0))
                            //返回Main主页
                            popProxy(R.id.mainFragment)
                        }
                    }
                })
            }
        }
    }

    /**
     * 频道管理
     */
    private fun channelManagement() {
        mBaseApiViewModel.requestUniversally(
                viewModelScope = lifecycleScope,
                isShowToastTip = false,
                request = { appDataManage ->
                    appDataManage.requestServerGroupList(mServerInfo.serverId)
                }
        ) { groups ->
            val data: ArrayList<Parcelable> = ArrayList()
            groups.content.forEach {
                data.add(ServerGroupIncludeEntity(1, it))
                it.channelVO.forEach { channelVO ->
                    channelVO.groupType = it.groupType
                    data.add(ServerGroupIncludeEntity(2, channelVO = channelVO))
                }
            }
            nav(R.id.action_serverSettingsFragment_to_channelManagementFragment, Bundle().apply {
                putParcelableArrayList(BUNDLE_DATA, data)
                putString(BUNDLE_SERVER_ID, mServerInfo.serverId)
            })
        }
    }

}



